#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
日历任务模块 - 处理提醒和通知
"""
import time
import threading
from datetime import datetime, timedelta
from ..database.connection import get_db_connection
from ..utils.email import send_email


class CalendarTaskManager:
    """日历任务管理器"""
    def __init__(self):
        self._running = False
        self._thread = None
        self._interval = 60  # 检查间隔（秒）
        self._check_ahead_minutes = 5  # 检查未来多少分钟内的提醒

    def set_check_ahead_minutes(self, minutes):
        """设置检查未来多少分钟内的提醒"""
        if minutes > 0:
            self._check_ahead_minutes = minutes

    def start(self):
        """启动任务管理器"""
        if self._running:
            return
        
        self._running = True
        self._thread = threading.Thread(target=self._run, daemon=True)
        self._thread.start()

    def stop(self):
        """停止任务管理器"""
        if not self._running:
            return
        
        self._running = False
        if self._thread:
            self._thread.join(timeout=5.0)

    def _run(self):
        """运行任务循环"""
        while self._running:
            try:
                self._check_reminders()
            except Exception as e:
                pass
            
            # 等待下一次检查
            for _ in range(self._interval):
                if not self._running:
                    break
                time.sleep(1)

    def _check_reminders(self):
        """检查需要发送的提醒"""
        now = datetime.now()
        future = now + timedelta(minutes=self._check_ahead_minutes)

        # 格式化时间为与数据库匹配的格式 (YYYY-MM-DDTHH:MM)
        now_str = now.strftime('%Y-%m-%dT%H:%M')
        future_str = future.strftime('%Y-%m-%dT%H:%M')

        conn = get_db_connection()
        cursor = conn.cursor()

        query = """
            SELECT ce.*, u.email
            FROM calendar_events ce
            JOIN users u ON ce.user_id = u.id
            WHERE ce.is_reminder = 1
              AND ce.reminder_time BETWEEN ? AND ?
              AND ce.reminder_sent = 0
        """
        params = (now_str, future_str)
        cursor.execute(query, params)
        
        events = cursor.fetchall()
        
        for event in events:
            
            # 尝试将事件标记为已安排提醒，避免重复设置定时器
            try:
                cursor.execute(
                    "UPDATE calendar_events SET reminder_sent = 2 WHERE id = ? AND reminder_sent = 0",
                    (event['id'],)
                )
                conn.commit()
                
                # 只有成功更新的事件才设置定时器
                if cursor.rowcount > 0:
                    # 解析提醒时间
                    reminder_time = datetime.strptime(event['reminder_time'], '%Y-%m-%dT%H:%M')
                    time_diff = (reminder_time - now).total_seconds()
                    

                    threading.Timer(max(0, time_diff), self._send_reminder_at_time, args=[event]).start()
                else:
                    pass
            except Exception as db_error:
                pass
        
        conn.close()

    def _send_reminder_at_time(self, event):
        """在指定时间发送提醒"""
        try:
            # 再次检查事件状态，确保没有被其他进程处理
            conn = get_db_connection()
            cursor = conn.cursor()
            cursor.execute(
                "SELECT reminder_sent FROM calendar_events WHERE id = ?",
                (event['id'],)
            )
            result = cursor.fetchone()
            
            # 检查事件状态，允许处理reminder_sent为2(已安排)的事件
            if result and result['reminder_sent'] in (0, 2):
                # 发送提醒邮件
                email_sent = self._send_reminder_email(event)
                
                if email_sent:
                    # 更新提醒状态
                    try:
                        cursor.execute(
                            "UPDATE calendar_events SET reminder_sent = 1 WHERE id = ?",
                            (event['id'],)
                        )
                        conn.commit()

                    except Exception as db_error:
                        pass
                else:
                    pass
            else:
                pass
            
            conn.close()
        except Exception as e:
            pass

    def _send_reminder_email(self, event):
        # 解析提醒时间
        reminder_time = datetime.strptime(event['reminder_time'], '%Y-%m-%dT%H:%M')
        """发送提醒邮件"""
        subject = f"【提醒】即将到来的事件: {event['title']}"
        body = f"""
        <h3>事件提醒</h3>
        <p>您好，提醒您即将到来的事件：</p>
        <p><strong>标题：</strong>{event['title']}</p>
        <p><strong>时间：</strong>{reminder_time}</p>
        <p><strong>描述：</strong>{event['description']}</p>
        <p>请提前做好准备。</p>
        <p>---</p>
        <p>此邮件由系统自动发送，请勿回复。</p>
        """
        
        try:
            result = send_email(event['email'], subject, body)
            if result:
                pass
            else:
                pass
                
            return result
        except Exception as e:
            return False


# 创建全局任务管理器实例
calendar_task_manager = CalendarTaskManager()


# 在应用启动时启动任务管理器
# 注意：在生产环境中，应该使用更可靠的方式来管理后台任务，如Celery